<template>
  <div>
    <el-space direction="vertical" alignment="left" style="width: 100%">
      <el-card>
        <el-form ref="searchFormComponents" :model="searchForm" inline>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="searchForm.username" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="searchForm.status" placeholder="请选择" clearable filterable style="width: 150px">
              <el-option :value="1" label="待付款"></el-option>
              <el-option :value="2" label="待发货"></el-option>
              <el-option :value="3" label="待收货"></el-option>
              <el-option :value="4" label="待评价"></el-option>
              <el-option :value="5" label="已完成"></el-option>
              <el-option :value="6" label="已取消"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收货人姓名" prop="name">
            <el-input v-model="searchForm.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="收货人电话" prop="tel">
            <el-input v-model="searchForm.tel" clearable></el-input>
          </el-form-item>
          <el-form-item label="收货人地址" prop="address">
            <el-input v-model="searchForm.address" clearable></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
        <el-space>
          <el-button type="danger" :icon="Delete" @click="batchDelete(null)" :disabled="selectionRows.length<=0">
            批量删除
          </el-button>
        </el-space>
      </el-card>
      <el-card>
        <el-table ref="tableComponents"
                  :data="listData"
                  tooltip-effect="dark"
                  style="width: 100%"
                  @selection-change="selectionChange"
                  border>
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="orderId" label="ID" width="50"></el-table-column>
          <el-table-column prop="name" label="商品名称"></el-table-column>
          <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <el-image style="width: 80px; height: 80px;" :src="scope.row.mainImg" fit="cover" />
            </template>
          </el-table-column>
          <el-table-column prop="sum" label="金额"></el-table-column>
          <el-table-column prop="number" label="数量"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <!-- 1，待付款  2，待发货  3，待收货  4，待评价  5，完成  6，取消 -->
              <el-tag v-if="scope.row.itemStatus === 1" type="warning">待付款</el-tag>
              <el-tag v-else-if="scope.row.itemStatus === 2" type="info">待发货</el-tag>
              <el-tag v-else-if="scope.row.itemStatus === 3" type="primary">待收货</el-tag>
              <el-tag v-else-if="scope.row.itemStatus === 4" type="success">待评价</el-tag>
              <el-tag v-else-if="scope.row.itemStatus === 5" type="success">已完成</el-tag>
              <el-tag v-else-if="scope.row.itemStatus === 6" type="danger">已取消</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="收货人姓名"></el-table-column>
          <el-table-column prop="tel" label="收货人电话"></el-table-column>
          <el-table-column prop="address" label="收货人地址" show-overflow-tooltip></el-table-column>
          <el-table-column prop="trackingNumber" label="物流单号"></el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createDate" label="创建时间"></el-table-column>
          <el-table-column fixed="right" label="高级操作" width="120">
            <template #default="scope">
              <el-button type="primary" v-if="scope.row.itemStatus === 2" :icon="Position"
                         @click="delivery(scope.$index, scope.row)">发货
              </el-button>

              <el-tag v-else-if="scope.row.itemStatus === 3" type="primary">待收货</el-tag>
              <el-tag v-else-if="scope.row.itemStatus === 4" type="success">待评价</el-tag>
              <el-tag v-else-if="scope.row.itemStatus === 5" type="success">已完成</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">
              <el-button :icon="Edit" @click="edit(scope.$index, scope.row)">编辑</el-button>
              <el-button :icon="Delete" type="danger" @click="deleteOne(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
          <el-pagination
              @current-change="currentChange"
              @size-change="sizeChange"
              :page-size="pageInfo.pageSize"
              :current-page="pageInfo.pageNum"
              background
              layout="total,sizes, prev, pager, next"
              :total="pageInfo.total">
          </el-pagination>
        </div>
      </el-card>
    </el-space>
    <el-dialog
        v-model="dialogOpen"
        v-if="dialogOpen"
        :title="formData.id?'编辑':'新增'"
        width="500"
    >
      <el-form ref="formRef" :model="formData" label-width="100px">
        <slot name="content">
          <el-form-item label="收货人姓名" prop="name"
                        :rules="[{required:true,message:'不能为空',trigger:[ 'blur','change']}]">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="收货人电话" prop="tel"
                        :rules="[{required:true,message:'不能为空',trigger:[ 'blur','change']}]">
            <el-input v-model="formData.tel"></el-input>
          </el-form-item>
          <el-form-item label="收货人地址" prop="address"
                        :rules="[{required:true,message:'不能为空',trigger:[ 'blur','change']}]">
            <el-input type="textarea" :rows="5" v-model="formData.address"></el-input>
          </el-form-item>
          <el-form-item label="物流单号" prop="trackingNumber">
            <el-input v-model="formData.trackingNumber"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :rows="5" v-model="formData.remark"></el-input>
          </el-form-item>
        </slot>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit" :icon="Check">提交</el-button>
          <el-button @click="closeDialog" :icon="Close">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/http.js";
import {Check, Close, Delete, Edit, Refresh, Plus, Search} from '@element-plus/icons-vue'
import {ref, toRaw} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

const searchFormComponents = ref();
const tableComponents = ref();
const listData = ref([]);
const pageInfo = ref({
  //当前页
  pageNum: 1,
  //分页大小
  pageSize: 10,
  //总条数
  total: 0
});
const searchForm = ref({
  username: undefined,
  status: undefined,
  name: undefined,
  tel: undefined,
  address: undefined
});

const statusList = ref(['待支付', '待发货', '待收货', '已完成', '已取消'])


getPageList()

/**
 * 获取分页数据
 */
function getPageList() {
  let data = Object.assign(toRaw(searchForm.value), toRaw(pageInfo.value));
  // Add qwe=0 parameter to indicate backend

  listData.value = []; // Reset the list before adding new items
  request.get("/api/productOrder/page", {
    params: data,
    qwe:0
  }).then(res => {
    if (res.code === 1) {
      // Process the nested data structure
      const ltd = res.data.list;
      console.log(ltd);
      for(let i=0; i<ltd.length; i++) {
        for(let j=0; j<ltd[i].productRts.length; j++) {
          let x = ltd[i].productRts[j];
          x.address = ltd[i].address;
          x.name = ltd[i].name;
          x.tel = ltd[i].tel;
          // Use item_status for individual product status if available
          x.status = x.item_status || ltd[i].status;
          x.createDate = ltd[i].createDate;
          x.remark = ltd[i].userMessage;
          x.trackingNumber = ltd[i].trackingNumber;
          // Include the order ID for actions
          x.orderId = ltd[i].oid;
          listData.value.push(x);
        }
      }
      pageInfo.value.total = res.data.total;
    } else {
      ElMessage.error(res.msg || "获取订单列表失败");
    }
  }).catch(error => {
    ElMessage.error("获取订单列表失败: " + error.message);
  });
}

/**
 * 选择分页
 * @param e
 */
function currentChange(e) {
  pageInfo.value.pageNum = e
  getPageList()
}

/**
 * 改变分页数量
 * @param e
 */
function sizeChange(e) {
  pageInfo.value.pageSize = e
  getPageList()
  console.log(e)
}

/**
 * 搜索
 */
function search() {
  pageInfo.value.pageNum = 1;
  getPageList();
}

/**
 * 重置搜索框
 */
function resetSearch() {
  searchFormComponents.value.resetFields();
  getPageList();
}

const dialogOpen = ref(false);
const formData = ref({});
const formRef = ref();

/**
 * 编辑
 * @param index
 * @param row
 */
function edit(index, row) {
  formData.value = {...row};
  // Ensure we're using the correct ID for the order
  formData.value.id = row.orderId || row.id;
  dialogOpen.value = true;
}
/**
 * 关闭弹框
 */
function closeDialog() {
  dialogOpen.value = false
}

/**
 * 提交数据
 */
function submit() {
  formRef.value.validate((valid) => {
    if (!valid) {
      ElMessage({
        message: "验证失败，请检查表单!",
        type: 'warning'
      });
      return;
    }
    //新增
    if (!formData.value.id) {
      request.post("/api/productOrder/add", formData.value).then(res => {
        if (res.code === 1) {
          dialogOpen.value = false;
        ElMessage({
            message: "添加成功",
          type: 'success'
        });
          getPageList();
        } else {
          ElMessage.error(res.msg || "添加失败");
        }
      }).catch(error => {
        ElMessage.error("添加失败: " + error.message);
      });
    } else {
      //更新
      request.put("/api/productOrder/update", formData.value).then(res => {
        if (res.code === 1) {
          dialogOpen.value = false;
        ElMessage({
            message: "更新成功",
          type: 'success'
        });
          getPageList();
        } else {
          ElMessage.error(res.msg || "更新失败");
        }
      }).catch(error => {
        ElMessage.error("更新失败: " + error.message);
      });
    }
  });
}

const selectionRows = ref([]);

/**
 * 多选
 * @param rows
 */
function selectionChange(rows) {
  selectionRows.value = rows
}

/**
 * 单个删除
 * @param index
 * @param row
 */
function deleteOne(index, row) {
  batchDelete([row])
}

/**
 * 批量删除
 * @param rows
 */
function batchDelete(rows) {
  if (!rows) {
    rows = selectionRows.value;
  }
  // Use orderId for each row
  let ids = rows.map(item => item.orderId || item.id);
  ElMessageBox.confirm(`此操作将永久删除ID为[${ids}]的数据, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(() => {
    request.delete("/api/productOrder/delBatch", {data: ids}).then(res => {
      if (res.code === 1) {
      ElMessage({
          message: "删除成功",
        type: 'success'
      });
        getPageList();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    }).catch(error => {
      ElMessage.error("删除失败: " + error.message);
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
    tableComponents.value.clearSelection();
  });
}

/**
 * 发货操作 - 直接发货，不需要输入物流单号
 */
function delivery(index, row) {
  // 获取订单ID和产品ID
  console.log(row)
  const oid = row.orderId
  const pid = row.id

  ElMessageBox.confirm(`确认发货此商品?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    // 直接调用发货API
    request.post("/api/productOrder/delivery", {
      oid: oid,
      pid: pid
    }).then(res => {
      if (res.code === 1) {
        ElMessage({
          message: "发货成功，商品状态已更新为待收货",
          type: 'success'
        });
        getPageList();
      } else {
        ElMessage.error(res.msg || "发货失败");
      }
    }).catch(error => {
      ElMessage.error("发货失败: " + error.message);
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消发货'
    });
  });
}

</script>

<style scoped>

</style>
